# -*- coding: utf-8 -*- 
# @Time : 2022/4/3 22:07 
# @Author : zzuxyj 
# @File : 11-nn-loss.py

"""
损失函数
L1Loss
MSELoss
CrossEntropyLoss
"""
import torch
from torch.nn import L1Loss, MSELoss, CrossEntropyLoss

input = torch.tensor([1, 2, 3], dtype=torch.float32)
target = torch.tensor([1, 2, 5], dtype=torch.float32)

input = torch.reshape(input, (1, 1, 1, 3))
target = torch.reshape(target, (1, 1, 1, 3))


# 测试L1Loss
def testL1Loss():
    loss = L1Loss(reduction='sum')  # reduction='mean' #(0 + 0 +2) / 3 # tensor(0.667)
    result_loss = loss(input, target)  # (0 + 0 + 2)  tensor(2 )
    print(result_loss)


def testMSELoss():
    loss = MSELoss()
    result_loss = loss(input, target)
    print(result_loss)  # ( 0+ 0 + 2*2) /3 #  tensor(1.3333)


def testCrossEntropyLoss():
    x = torch.tensor([0.1, 0.2, 0.3])
    y = torch.tensor([1])
    x = torch.reshape(x, (1, 3))  # (batch_size , size)
    loss_cross = CrossEntropyLoss()
    result_loss = loss_cross(x, y)
    print(result_loss) # tensor(1.1019)   # 交叉熵公式


if __name__ == '__main__':
    testCrossEntropyLoss()
